package com.example.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.dto.AirspaceDemandIdQueryBDTO;
import com.example.dto.AirspaceDemandPageQueryBDTO;
import com.example.dto.AirspaceDemandPageQueryDTO;
import com.example.dto.AirspaceDemandReviewDTO;
import com.example.entity.*;
import com.example.mapper.AirspaceDemandMapper;
import com.example.mapper.AirspaceDemandMiniMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class AirspaceDemandService {

    @Autowired
    private AirspaceDemandMapper airspaceDemandMapper;
    private AirspaceDemandMiniMapper airspaceDemandMiniMapper;
    //根据id查询
//    public Optional<AirspaceDemandIdQueryBDTO> findById(Integer id) {
//        AirspaceDemand airspaceDemand = airspaceDemandMapper.selectById(id);
//        AirspaceDemandIdQueryBDTO airspaceDemandIdQueryBDTO = new AirspaceDemandIdQueryBDTO();
//        if (airspaceDemand != null) {
//
//            airspaceDemandIdQueryBDTO.setId(airspaceDemand.getId());
//            airspaceDemandIdQueryBDTO.setUserName(airspaceDemand.getUserName());
//            airspaceDemandIdQueryBDTO.setApplicationAcceptanceTime(airspaceDemand.getApplicationAcceptanceTime());
//            airspaceDemandIdQueryBDTO.setApplicationId(airspaceDemand.getApplicationId());
//            airspaceDemandIdQueryBDTO.setApprovalStatus(airspaceDemand.getApprovalStatus());
//            airspaceDemandIdQueryBDTO.setApplicant(airspaceDemand.getApplicant());
//            airspaceDemandIdQueryBDTO.setContacts(airspaceDemand.getContacts());
//            airspaceDemandIdQueryBDTO.setTelephone(airspaceDemand.getTelephone());
//            airspaceDemandIdQueryBDTO.setAircraftManufacturer(airspaceDemand.getAircraftManufacturer());
//            airspaceDemandIdQueryBDTO.setAircraftModel(airspaceDemand.getAircraftModel());
//            airspaceDemandIdQueryBDTO.setAircraftType(airspaceDemand.getAircraftType());
//            airspaceDemandIdQueryBDTO.setAircraftControlType(airspaceDemand.getAircraftControlType());
//            airspaceDemandIdQueryBDTO.setMaximumTakeoffWeight(airspaceDemand.getMaximumTakeoffWeight());
//            airspaceDemandIdQueryBDTO.setDimensionsOfAircraftInDeployedState(airspaceDemand.getDimensionsOfAircraftInDeployedState());
////            airspaceDemandIdQueryBDTO.setAirspaceUsageType(airspaceDemand.getAirspaceUsageType());
//            airspaceDemandIdQueryBDTO.setTaskType(airspaceDemand.getTaskType());
//            airspaceDemandIdQueryBDTO.setTaskStartTime(airspaceDemand.getTaskStartTime());
//            airspaceDemandIdQueryBDTO.setTaskEndTime(airspaceDemand.getTaskEndTime());
//            airspaceDemandIdQueryBDTO.setMaximumFlightAltitude(airspaceDemand.getMaximumFlightAltitude());
//            airspaceDemandIdQueryBDTO.setMinimumFlightAltitude(airspaceDemand.getMinimumFlightAltitude());
//            airspaceDemandIdQueryBDTO.setIsRoundTrip(airspaceDemand.getIsRoundTrip());
//            airspaceDemandIdQueryBDTO.setFlightFrequency(airspaceDemand.getFlightFrequency());
//            airspaceDemandIdQueryBDTO.setTakeoffLocationName(airspaceDemand.getTakeoffLocationName());
//            airspaceDemandIdQueryBDTO.setTakeoffLocationCode(airspaceDemand.getTakeoffLocationCode());
//            airspaceDemandIdQueryBDTO.setTakeoffLocationType(airspaceDemand.getTakeoffLocationType());
//
//            String takeoffLocationCoordinatesJson = airspaceDemand.getTakeoffLocationCoordinates();
//            if (takeoffLocationCoordinatesJson!=null&& !takeoffLocationCoordinatesJson.isEmpty())
//            {
//                IPosition2 takeoffLocationCoordinatesPosition = JSON.parseObject(takeoffLocationCoordinatesJson, IPosition2.class);
//                airspaceDemandIdQueryBDTO.setTakeoffLocationCoordinates(takeoffLocationCoordinatesPosition);
//            }
//            else
//            {
//                airspaceDemandIdQueryBDTO.setTakeoffLocationCoordinates(null);
//            }
//
//
//            airspaceDemandIdQueryBDTO.setLandingLocationName(airspaceDemand.getLandingLocationName());
//            airspaceDemandIdQueryBDTO.setLandingLocationCode(airspaceDemand.getLandingLocationCode());
//            airspaceDemandIdQueryBDTO.setLandingLocationType(airspaceDemand.getLandingLocationType());
//            String landingLocationCoordinatesJson = airspaceDemand.getLandingLocationCoordinates();
//            if (landingLocationCoordinatesJson!=null&& !landingLocationCoordinatesJson.isEmpty())
//            {
//
//                IPosition2 landingLocationCoordinatesPosition = JSON.parseObject(landingLocationCoordinatesJson, IPosition2.class);
//                airspaceDemandIdQueryBDTO.setLandingLocationCoordinates(landingLocationCoordinatesPosition);
//            }
//            else
//            {
//                airspaceDemandIdQueryBDTO.setLandingLocationCoordinates(null);
//            }
//
//            airspaceDemandIdQueryBDTO.setAirspaceType(airspaceDemand.getAirspaceType());
//            String waypointsCoordinatesJson = airspaceDemand.getWaypointsCoordinates();
//
//            if (waypointsCoordinatesJson!=null&& !waypointsCoordinatesJson.isEmpty())
//            {
//                JSONArray waypointsCoordinatesJsonArray = JSON.parseArray(waypointsCoordinatesJson);
//                List<IPosition1> waypointsCoordinatesPositionList = waypointsCoordinatesJsonArray.toJavaList(IPosition1.class);
//
//                airspaceDemandIdQueryBDTO.setWaypointsCoordinates(waypointsCoordinatesPositionList);
//            }
//            else
//            {
//                airspaceDemandIdQueryBDTO.setWaypointsCoordinates(null);
//            }
//
//            String circleCenterCoordinatesJson = airspaceDemand.getCircleCenterCoordinates();
//            if(circleCenterCoordinatesJson!=null&& !circleCenterCoordinatesJson.isEmpty())
//            {
//                IPosition1 circleCenterCoordinatesPosition = JSON.parseObject(circleCenterCoordinatesJson, IPosition1.class);
//                airspaceDemandIdQueryBDTO.setCircleCenterCoordinates(circleCenterCoordinatesPosition);
//            }
//            else
//            {
//                airspaceDemandIdQueryBDTO.setCircleCenterCoordinates(null);
//            }
//            airspaceDemandIdQueryBDTO.setRadius(airspaceDemand.getRadius());
//            return Optional.of(airspaceDemandIdQueryBDTO);
//        }
//        else
//        {
//            return Optional.empty();
//        }
//    }
    //根据申请id查询用户
    public Optional<AirspaceDemandIdQueryBDTO> getByApplicationId(String applicationId)
    {
        QueryWrapper<AirspaceDemand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("application_id",applicationId);//
        AirspaceDemand airspaceDemand = airspaceDemandMapper.selectOne(queryWrapper);

        AirspaceDemandIdQueryBDTO airspaceDemandIdQueryBDTO = new AirspaceDemandIdQueryBDTO();
        if (airspaceDemand != null) {
            BeanUtils.copyProperties(airspaceDemand,airspaceDemandIdQueryBDTO);

            String takeoffLocationCoordinatesJson = airspaceDemand.getTakeoffLocationCoordinates();
            if (takeoffLocationCoordinatesJson!=null&& !takeoffLocationCoordinatesJson.isEmpty())
            {
                IPosition3 takeoffLocationCoordinatesPosition = JSON.parseObject(takeoffLocationCoordinatesJson, IPosition3.class);
                airspaceDemandIdQueryBDTO.setTakeoffLocationCoordinates(takeoffLocationCoordinatesPosition);
            }
            String landingLocationCoordinatesJson = airspaceDemand.getLandingLocationCoordinates();
            if (landingLocationCoordinatesJson!=null&& !landingLocationCoordinatesJson.isEmpty())
            {

                IPosition3 landingLocationCoordinatesPosition = JSON.parseObject(landingLocationCoordinatesJson, IPosition3.class);
                airspaceDemandIdQueryBDTO.setLandingLocationCoordinates(landingLocationCoordinatesPosition);
            }
            String polygonalWaypointsCoordinatesJson=airspaceDemand.getPolygonalWaypointsCoordinates();
            if (polygonalWaypointsCoordinatesJson!=null && !polygonalWaypointsCoordinatesJson.isEmpty())
            {
                JSONArray polygonalWaypointsCoordinatesJsonArray = JSON.parseArray(polygonalWaypointsCoordinatesJson);
                List<IPosition1> polygonalWaypointsCoordinatesPositionList = polygonalWaypointsCoordinatesJsonArray.toJavaList(IPosition1.class);
                airspaceDemandIdQueryBDTO.setPolygonalWaypointsCoordinates(polygonalWaypointsCoordinatesPositionList);
            }

            String straightWaypointsCoordinatesJson = airspaceDemand.getStraightWaypointsCoordinates();
            if (straightWaypointsCoordinatesJson!=null&& !straightWaypointsCoordinatesJson.isEmpty())
            {
                JSONArray straightWaypointsCoordinatesJsonArray = JSON.parseArray(straightWaypointsCoordinatesJson);
                List<IPosition2> straightWaypointsCoordinatesList = straightWaypointsCoordinatesJsonArray.toJavaList(IPosition2.class);
                airspaceDemandIdQueryBDTO.setStraightWaypointsCoordinates(straightWaypointsCoordinatesList);
            }

            String circleCenterCoordinatesJson = airspaceDemand.getCircleCenterCoordinates();
            if(circleCenterCoordinatesJson!=null&& !circleCenterCoordinatesJson.isEmpty())
            {
                JSONArray circleCenterCoordinatesPositionJsonArray=JSON.parseArray(circleCenterCoordinatesJson);
                List<IPosition4> circleCenterCoordinatesPositionList=circleCenterCoordinatesPositionJsonArray.toJavaList(IPosition4.class);
                airspaceDemandIdQueryBDTO.setCircleCenterCoordinates(circleCenterCoordinatesPositionList);
            }
            return Optional.of(airspaceDemandIdQueryBDTO);
        }
        else
        {
            return Optional.empty();
        }
    }
    //根据id修改申请状态
        public Optional<AirspaceDemand> update(AirspaceDemandReviewDTO airspaceDemandReviewDTO) {
        String applicationId=airspaceDemandReviewDTO.getApplicationId();
        QueryWrapper<AirspaceDemand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("application_id",applicationId);//
        AirspaceDemand airspaceDemand = airspaceDemandMapper.selectOne(queryWrapper);

        if (airspaceDemand == null) {
            return Optional.empty();
        }
        if (airspaceDemand.getApprovalStatus().equals(airspaceDemandReviewDTO.getNewApprovalStatus())) {
            return Optional.of(airspaceDemand);
        }
        else
        {
            airspaceDemand.setApprovalStatus(airspaceDemandReviewDTO.getNewApprovalStatus());
            airspaceDemandMapper.updateById(airspaceDemand);
            return Optional.of(airspaceDemand);
        }
    }

    //用户需求页面查询
    public AirspaceDemandPageQueryBDTO<AirspaceDemandMini> page(AirspaceDemandPageQueryDTO airspaceDemandPageQueryDTO){
        // 获取分页参数和搜索字符串
        int currentPage = airspaceDemandPageQueryDTO.getCurrentPage();
        int size = airspaceDemandPageQueryDTO.getSize();
        String userName = airspaceDemandPageQueryDTO.getUserName();
        String order = airspaceDemandPageQueryDTO.getOrder();
        Integer approvalStatus = airspaceDemandPageQueryDTO.getApprovalStatus();
        String applicationId= airspaceDemandPageQueryDTO.getApplicationId();

        QueryWrapper<AirspaceDemand> queryWrapper = new QueryWrapper<>();
        // 如果传入了 keyText，则对多个字段进行模糊匹// 如果传入了 keyText，则对多个字段进行模糊匹配
        if (applicationId != null && !applicationId.isEmpty()) {
            queryWrapper.lambda().like(AirspaceDemand::getApplicationId, applicationId);
        }
        if (approvalStatus != null) {
            queryWrapper.and(e->e.lambda().eq(AirspaceDemand::getApprovalStatus, approvalStatus));
        }
        if (userName != null) {
            queryWrapper.and(e->e.lambda().eq(AirspaceDemand::getUserName, userName));
        }
        // 根据排序规则决定是按时间最新（降序）还是最晚（升序）
        if ("时间最新".equals(order)) {
            queryWrapper.orderByDesc("application_acceptance_time");
        } else if ("时间最晚".equals(order)) {
            queryWrapper.orderByAsc("application_acceptance_time");
        }
        // 执行分页查询
        Page<AirspaceDemand> page = new Page<>(currentPage, size);
        Page<AirspaceDemand> airspaceDemandSearchPage = airspaceDemandMapper.selectPage(page,queryWrapper);
        //搜索后数据处理
        int total = (int) airspaceDemandSearchPage.getTotal();
        int pageSize = (int)page.getSize();
        List<AirspaceDemandMini> airspaceDemandMinis = new ArrayList<>();

        AirspaceDemandPageQueryBDTO<AirspaceDemandMini> airspaceDemandPageQueryBDTO = new AirspaceDemandPageQueryBDTO<>();

        // 将查询结果转换为 DTO
        for (AirspaceDemand demand : airspaceDemandSearchPage.getRecords()) {
            AirspaceDemandMini airspaceDemandMini = new AirspaceDemandMini();
            airspaceDemandMini.setId(demand.getId());
            airspaceDemandMini.setUserName(demand.getUserName());
            airspaceDemandMini.setApplicationAcceptanceTime(demand.getApplicationAcceptanceTime());
            airspaceDemandMini.setApplicationId(demand.getApplicationId());
            airspaceDemandMini.setApprovalStatus(demand.getApprovalStatus());
            airspaceDemandMinis.add(airspaceDemandMini);
        }
        airspaceDemandPageQueryBDTO.setTotal(total);
        airspaceDemandPageQueryBDTO.setPageData(airspaceDemandMinis);
        airspaceDemandPageQueryBDTO.setPageNum(currentPage);
        airspaceDemandPageQueryBDTO.setPageSize(size);
        Integer pages = (int) Math.ceil((double) total / pageSize);//计算搜寻关键字后的数据总页数
        airspaceDemandPageQueryBDTO.setPages(pages);
        return airspaceDemandPageQueryBDTO;
    }

}
